import {
  genChartByAiAsyncMqUsingPost,
} from '@/services/shanbi/chartController';
import { UploadOutlined } from '@ant-design/icons';
import { Button, Form, Select, Space, Upload, message } from 'antd';
import TextArea from 'antd/es/input/TextArea';
import React, {useEffect, useState} from 'react';
import {useForm} from "antd/es/form/Form";
import {useModel} from "@@/exports";

const AddChartAsync: React.FC = () => {
  const [form]=useForm();
  const [submitting, setsubmintting] = useState<boolean>(false);
  const [socket, setSocket] = useState(null);
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState ?? {};

  useEffect(() => {
    const ws = new WebSocket('ws://localhost:8101/api//webSocketToUser/'+currentUser.id);

    ws.onopen = () => {
      console.log('Connected to WebSocket server');
      ws.send("sb")
    };

    ws.onmessage = (event) => {
      const messageFromServer = event.data;
      console.log('成功')
      message.success(messageFromServer); // 使用Ant Design Message组件显示消息
    };

    ws.onerror = (error) => {
      console.error('WebSocket Error: ', error);
    };
    ws.onclose = (event) => {
      if (event.wasClean) {
        console.log('Closed cleanly, code:', event.code, 'reason:', event.reason);
      } else {
        console.error('Connection died');
      }
    };

    setSocket(ws);

    return () => {
      if (socket) {
        socket.close();
      }
    };
  }, []);

  const onFinish = async (values: any) => {
    //避免重复提交
    if (submitting) {
      return;
    }
    setsubmintting(true);
    // console.log('用户保存内容: ', values);
    const params = {
      ...values,
      file: undefined,
    };
    try {
      const res = await genChartByAiAsyncMqUsingPost(params, {}, values.file.file.originFileObj);
      if (!res?.data) {
        message.error('分析失败');
      } else {
        message.success('分析任务提交成功,稍后在我的图表页面查看');
        form.resetFields();
      }
    } catch (e: any) {
      message.error('分析失败，' + e.message);
    }
    setsubmintting(false);
  };

  return (
    <div className="add-chart">
      <Form
        form={form}
        name="addChart"
        labelAlign="left"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
        initialValues={{}}
      >
        <Form.Item
          name="goal"
          label="分析目标"
          rules={[{ required: true, message: '请输入分析目标' }]}
        >
          <TextArea placeholder="请输入你的分析需求，比如：分析网站的用户增长情况" />
        </Form.Item>
        <Form.Item name="name" label="图表名称">
          <TextArea />
        </Form.Item>
        <Form.Item name="chartType" label="图表类型">
          <Select
            options={[
              { value: '折线图', label: '折线图' },
              { value: '柱状图', label: '柱状图' },
              { value: '堆叠图', label: '堆叠图' },
              { value: '饼图', label: '饼图' },
              { value: '雷达图', label: '雷达图' },
            ]}
          ></Select>
        </Form.Item>

        <Form.Item name="file" label="原始数据">
          <Upload name="file" maxCount={1}>
            <Button icon={<UploadOutlined />}>上传 CSV 文件</Button>
          </Upload>
        </Form.Item>

        <Form.Item wrapperCol={{ span: 12, offset: 4 }}>
          <Space>
            <Button
              type="primary"
              htmlType="submit"
              loading={submitting}
              disabled={submitting}
            >
              提交
            </Button>
            <Button htmlType="reset">重置</Button>
          </Space>
        </Form.Item>
      </Form>
    </div>
  );
};
export default AddChartAsync;
